<template>
  <div v-if="isVisible" class="modal-overlay" @click.self="close">
    <div class="modal-content">
      <span class="close-button" @click="close">&times;</span>
      <h2>{{ isPhoneLogin ? '手机号登录' : '会员登录/注册' }}</h2>

      <div v-if="!isPhoneLogin">
        <input v-model="accountUsername" type="text" placeholder="请输入用户名" />
        <input v-model="accountPassword" type="password" placeholder="请输入密码" />
        <div class="button-group">
          <button @click="loginWithUsername" :disabled="isLoading">
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
          <button @click="register" class="register-button">注册</button>
        </div>
        <p @click="toggleLoginMethod" class="toggle-link">使用手机号登录</p>
      </div>

      <div v-else>
        <input v-model="phone" type="text" placeholder="请输入手机号" />
        <input v-model="code" type="text" placeholder="请输入验证码" />
        <div class="button-group">
          <button @click="getCode">获取验证码</button>
          <button @click="loginWithPhone">登录</button>
          <button @click="register">注册</button>


        </div>
        <p @click="toggleLoginMethod" class="toggle-link">使用用户名和密码登录</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  width: 380px;
  border-radius: 16px;
  padding: 32px 36px 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  text-align: center;
  position: relative;
  z-index: 1000;
  overflow: visible !important;  /* 确保内容不会被裁剪 */
}

.close-button {
  position: absolute;
  top: 16px;
  right: 20px;
  font-size: 24px;
  color: #999;
  cursor: pointer;
}

input {
  width: 100%;
  border: 1px solid #ddd;
  padding: 14px 16px;
  border-radius: 8px;
  margin: 10px 0;
  font-size: 15px;
  transition: 0.2s;
}

input:focus {
  border-color: #1abc9c;
  outline: none;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  position: relative;
  z-index: 1000;
}

button {
  flex: 1;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  padding: 14px;
  cursor: pointer;
  opacity: 1 !important;
  z-index: 1000 !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

button:not(.register-button) {
  background: #1abc9c;
  color: #fff;
}

button:not(.register-button):hover {
  background: #16a085;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.register-button {
  background: #ecf0f1;
  color: #2c3e50;
}

.register-button:hover {
  background: #d9e1e4;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.toggle-link {
  margin-top: 15px;
  color: #1abc9c;
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
}

.toggle-link:hover {
  color: #16a085;
}
</style>
<script>
import {BASE_URL} from "@/util/Config.js";
import { useUserStore } from '@/stores/user';
import axios from 'axios';
import {nextTick} from "vue";
export default {
  props: {
    isVisible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      isPhoneLogin: false,
      accountUsername: '',
      accountPassword: '',
      phone: '',
      code: '',
      isLoading: false,
    };
  },
  methods: {
    register() {
      this.$emit('open-register'); // 替换原来的路由跳转
    },
    close() {
      this.$emit('close'); // 关闭模态窗口
    },
    toggleLoginMethod() {
      this.isPhoneLogin = !this.isPhoneLogin;
    },
    async getCode () {
      const phone = this.phone.trim()
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号')
        return
      }

      try {
        // 注意：body 里字段名必须是 userPhone
        await axios.post(BASE_URL+'/user/sendCode', {
          userPhone: phone
        })
        alert(`验证码已发送到 ${phone}`)
      } catch (e) {
        console.error(e)
        alert('短信发送失败')
      }
    },
    async loginWithUsername() {
      try {
        const response = await fetch(BASE_URL + '/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            accountUsername: this.accountUsername,
            accountPassword: this.accountPassword
          })
        });

        const data = await response.json();
        console.log('完整登录响应:', data); // 确认数据结构

        if (data.code === 200) {
          // 强制类型检查（确保后端返回字段名匹配）
          const userData = {
            userId: String(data.data?.userId || data.data?.id), // 兼容不同命名
            token: data.data?.token,
            accountRole: data.data?.accountRole
          };

          if (!userData.userId) throw new Error("后端未返回userId");

          // 存储到 Pinia 和 localStorage
          const userStore = useUserStore();
          userStore.setUserInfo(userData);

          // 同步到 localStorage（解决首次持久化延迟）
          localStorage.setItem('user_info', JSON.stringify(userData));

          // 跳转前验证存储
          console.log('当前Store:', userStore.$state);
          console.log('localStorage:', localStorage.getItem('user_info'));

          // 跳转时强制等待状态同步
          await nextTick();
          this.$router.push('/order').then(() => {
            location.reload(); // 跳转后刷新页面
          });

        }
      } catch (error) {
        console.error('登录失败:', error);
        alert(`登录失败: ${error.message}`);
      }
    },
    // async loginWithUsername() {
    //   try {
    //     const { accountUsername, accountPassword } = this;
    //     if (!accountUsername || !accountPassword) {
    //       alert("用户名和密码不能为空");
    //       return;
    //     }
    //
    //     if (this.isLoading) return;
    //     this.isLoading = true;
    //
    //     const response = await fetch(BASE_URL+'/login', {
    //       method: 'POST',
    //       headers: { 'Content-Type': 'application/json' },
    //       body: JSON.stringify({ accountUsername, accountPassword })
    //     });
    //
    //     if (!response.ok) throw new Error(`HTTP ${response.status}`);
    //     const data = await response.json(); // 假设后端总是返回 JSON
    //     if (!data) throw new Error("空响应");
    //
    //     console.log("响应数据:", data.data);
    //
    //     if (data.code === 200 && data.data.accountRole === "1") {
    //
    //       // ✨ 2. 在这里集成 Pinia
    //       // 获取 store 实例
    //       const userStore = useUserStore();
    //       // 调用 action 存储用户信息
    //       userStore.setUserInfo(data.data);
    //       alert("登录成功");
    //       // 手动同步到 localStorage（解决首次持久化延迟问题）
    //       localStorage.setItem('user_info', JSON.stringify({
    //         userId: data.data.userId
    //       }));
    //
    //       // 跳转前打印调试信息
    //       console.log('当前 Store:', userStore.$state);
    //       console.log('localStorage:', localStorage.getItem('user_info'));
    //       // 3. 登录成功后跳转到主页
    //       console.log('准备跳转 /order');
    //       this.$router.push('/order').then(() => {
    //         this.close();   // 路由真正完成后再关闭弹窗
    //       });
    //       console.log('已调用 push');
    //     } else {
    //       alert(data.message || "登录失败");
    //     }
    //   } catch (error) {
    //     console.error('登录错误:', error);
    //     alert(error.message.includes("JSON")
    //         ? "服务器返回数据格式错误"
    //         : "登录失败，请检查网络或联系管理员");
    //   } finally {
    //     this.isLoading = false;
    //   }
    // }
    // ,
    handleRegister() {
      emit('open-register');
    },
    async loginWithPhone() {
      // 处理手机号登录逻辑
      try {
        // 表单验证
        const {phone, code} = this;
        if (!phone || !code) {
          alert("手机号和验证码不能为空");
          return;
        }

        if (!/^1[3-9]\d{9}$/.test(phone)) {
          alert("请输入正确的手机号格式");
          return;
        }

        // 防重复提交
        if (this.isLoading) return;
        this.isLoading = true;

        // 发送请求
        const response = await fetch(BASE_URL+'/user/loginduanxin', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({phone, code})
        });

        // 处理响应
        if (!response.ok) throw new Error(`HTTP ${response.status}`);

        const text = await response.text();
        const data = text ? JSON.parse(text) : null;

        if (!data) throw new Error("空响应");

        if (data.code === 200) {
          alert("登录成功");
          const userStore = useUserStore();
          // 调用 action 存储用户信息
          userStore.setUserInfo(data.data);

          // 存储token示例: localStorage.setItem('token', data.token);
          console.log('准备跳转 /order');
          this.$router.push('/order').then(() => {
            this.close();   // 路由真正完成后再关闭弹窗
          });
        } else {
          alert(data.message || "登录失败");
        }
      } catch (error) {
        console.error('手机号登录错误:', error);
        alert(error.message.includes("JSON")
            ? "服务器返回数据格式错误"
            : error.message);
      } finally {
        this.isLoading = false;
      }

    }

  },


}
</script>

